package cn.practice.chat.service.impl;

import cn.hutool.extra.pinyin.PinyinUtil;
import cn.practice.chat.mapper.UserFriendMapper;
import cn.practice.chat.response.chat.TransferData;
import cn.practice.chat.response.friend.FriendResponse;
import cn.practice.chat.response.user.LoginUser;
import cn.practice.chat.service.FriendService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;

/**
 * @ClassName FriendServiceImpl
 * @Description:
 * @Author A-TAO
 * @Date 2022/11/5
 * @Version V1.0
 **/
@Service
@Slf4j
public class FriendServiceImpl implements FriendService {

    @Autowired
    private UserFriendMapper userFriendMapper;


    @Override
    public List<FriendResponse> getFriends(LoginUser loginUser) {

        List<FriendResponse> responses = null;
        List<FriendResponse> friendList = userFriendMapper.userFriendList(loginUser.getUserId());
        log.info("查询userid={}好友列表，result={}", loginUser.getUserId(), friendList);
        if(!CollectionUtils.isEmpty(friendList)){
            List<String> initials = new ArrayList<>();
            for(FriendResponse response: friendList){
                setInitial(response);
            }
            responses =  friendList.stream().sorted(Comparator.comparing(FriendResponse::getInitial)).collect(Collectors.toList());
            for(FriendResponse response: responses){
                if(initials.contains(response.getInitial())){
                    response.setInitial(null);
                }else{
                    initials.add(response.getInitial());
                }
            }
        }
        return responses;
    }

    @Override
    public List<TransferData> getTransferDataList(LoginUser loginUser) {

        List<TransferData> transferList = userFriendMapper.transferDataList(loginUser.getUserId());
        if(!CollectionUtils.isEmpty(transferList)){
            for(TransferData data : transferList){
                String pinyin = PinyinUtil.getPinyin(data.getLabel()).replace(" ","");
                data.setPinyin(pinyin);
            }
        }
        return transferList;
    }


    private void setInitial(FriendResponse response){
        String str1 = PinyinUtil.getFirstLetter(response.getNick(),"-");
        String a = (str1.split("-")[0]).toUpperCase(Locale.ROOT);
        response.setInitial(a);
    }
}
